define(['ui'], function (require, exports, module) {

    var breed;

    function bind(obj) {
        obj.autocomplete({
            source: breed,
            minLength: 0,
            scrollHeight: 300,
            change: function (e, ui) {
                var o = $(e.target);
            }
        }).focus(function () {
            obj.autocomplete('search');
        });
    }

    function bindMu(obj) {
        obj.autocomplete({
            source: breed,
            minLength: 0,
            scrollHeight: 300,
            change: function(e, ui) {
                var o = $(e.target);
            },
            source: function( request, response ) {
                // delegate back to autocomplete, but extract the last term
                response( $.ui.autocomplete.filter(
                    breed, request.term.split( /,\s*/).pop()
                ));
            },
            select: function( event, ui ) {
                var terms = this.value.split( /,\s*/ );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        }).focus(function () {
            obj.autocomplete('search');
        });
    }

    function setBreed(fn, obj) {
        $.ajax({
            url: '/Ajax/User/getBreed?stmp=' + new Date().toString,
            dataType: 'json',
            success: function(d) {
                if (d.error) {
                    alert(d.data);
                } else {
                    breed = d.data;
                    fn(obj);
                }
            }
        });
    }

    exports.init = function (obj) {
        obj = $(obj);
        if (breed) {
            bind(obj);
        } else {
            setBreed(bind, obj);
        }
    }
    exports.muInit = function (obj) {
        obj = $(obj);
        if (breed) {
            bindMu(obj);
        } else {
            setBreed(bindMu, obj);
        }
    }
});